package cn.acewill.yxd.yunxundian.ui.sign;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.OnApplyWindowInsetsListener;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.WindowInsetsCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.ScheduleRecycleAdapter;
import cn.acewill.yxd.yunxundian.model.CommonMapBean;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.model.tReportMain;
import cn.acewill.yxd.yunxundian.model.tempLostRR;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.pubClass.signuppanel;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.utils.CacheActivity;
import cn.acewill.yxd.yunxundian.utils.Eyes;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;
import cn.acewill.yxd.yunxundian.utils.TopDialogUtils;

import static cn.finalteam.toolsfinal.DeviceUtils.getStatusBarHeight;

/**
 * Created by AAA on 2017/4/7.
 */

public class EvaluationMianActivity extends AppCompatActivity implements View.OnClickListener{
    protected YXDAPP yxdapp=new YXDAPP();
    protected  DbManager db = x.getDb(yxdapp.getDaoConfig());
    private Button sureSearch;
    private List<Schedule> dataList;
    private EditText taskSearch;
    /*当前时间*/
    private String currentDate;
    /*选择更多的dialog*/
    private Dialog dialog;
    /*不同跳转传递过来的标识*/
    private int LOADWHAT;
    /*选中的schid*/
    public  int schid;
    private ScheduleRecycleAdapter adapter;
    public  int shopid=0;
    public  int count=0;
    private int year,month,thisyear,thismonth;
    /*判断选取的职能或者是默认的标识去加载上下月数据*/
    private int chechLodaId=0;
    private RecyclerView myRecycle;
    private CollapsingToolbarLayout myCollap;
    private ProgressDialog pdialog;
    private Handler handler=new Handler();
    //无数据显示
    private LinearLayout erroLinear;
    private TextView erroText;
    private String shopName="";
    private List<Schedule> noScoreList;
    private List<tReportMain> mainList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.evaluation_main_list);
        initView();
        CacheActivity.addActivity(this);
        initRecycleView();
        LoadDate(currentDate);
        try {
            loadSchScore();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void initView(){
        LOADWHAT=getIntent().getIntExtra("label",-1);
        shopid=getIntent().getIntExtra("shopid",0);
        Button moreBtn = (Button) findViewById(R.id.MoreBtn);
        moreBtn.setOnClickListener(this);
        this.taskSearch= (EditText) findViewById(R.id.taskSearch);
        this.sureSearch= (Button) findViewById(R.id.sureSearch);
        erroLinear= (LinearLayout) findViewById(R.id.erroLinear);
        erroText= (TextView) findViewById(R.id.erroText);
        myRecycle= (RecyclerView) findViewById(R.id.myRecycle);
        Toolbar myToolBar = (Toolbar) findViewById(R.id.myToolBar);
        setSupportActionBar(myToolBar);
        myToolBar.setNavigationIcon(R.mipmap.back);
        myToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        myCollap= (CollapsingToolbarLayout) findViewById(R.id.myCollap);
        ImageView userPhoto = (ImageView) findViewById(R.id.userPhoto);
        AppBarLayout myAppBar = (AppBarLayout) findViewById(R.id.myAppBar);
        Eyes.setStatusBarColorForCollapsingToolbar(this, myAppBar, myCollap, myToolBar, ContextCompat.getColor(this, R.color.blue));


        try {
            if (shopid!=0){
                shopName = db.selector(Shop.class).where("ID","=",shopid).findFirst().getShopName();
            }
            if (shopName==null){
                shopName="";
            }
            Employee employee=db.selector(Employee.class).where("ID","=",MainActivity.id).findFirst();
            if (employee.getEmpImage()==null){
                userPhoto.setImageResource(R.mipmap.icon_logo);
            }else{
                String path=pubClass.pictureSavePath+employee.getEmpImage();
                Glide.with(this).load(path).
                        diskCacheStrategy(DiskCacheStrategy.NONE)
                        .skipMemoryCache(true)
                        .error(R.mipmap.icon_error).into(userPhoto);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM", Locale.getDefault());
        currentDate = sdf.format(date); // 当期日期
        String[] mytime=currentDate.split("-");
        year=Integer.parseInt(mytime[0]);
        month=Integer.parseInt(mytime[1]);
        thisyear=Integer.parseInt(mytime[0]);
        thismonth=Integer.parseInt(mytime[1]);
        myCollap.setTitle(shopName+"评估 "+"("+month+"月"+")");
        taskSearch.setHint("餐厅名称或开始日期 (如："+BaseActivity.getMonth_Year_day()+")");
        LimitsEditEnter(taskSearch);
        sureSearch.setEnabled(false);
        sureSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.post(runnable);
            }
        });
        //搜索监听
        taskSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                //改变后判断是否可点击
                String text = taskSearch.getText().toString().trim();
                if (TextUtils.isEmpty(text)){
                    sureSearch.setEnabled(false);
                    //返回原来数据状态
                        setmyAdapter(dataList);
                        myRecycle.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                }else{
                    sureSearch.setEnabled(true);
                }
            }
        });

    }

    public void initRecycleView(){
        LinearLayoutManager manager=new LinearLayoutManager(this);
        myRecycle.setLayoutManager(manager);
        manager.setOrientation(OrientationHelper.VERTICAL);
        //防止滑动冲突
        myRecycle.setNestedScrollingEnabled(false);
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(EvaluationMianActivity.this)
                .setMessage(message)
                .setPositiveButton("确定", okListener)
                .setNegativeButton("取消", null)
                .create()
                .show();
    }
    Runnable runnable=new Runnable() {
        @Override
        public void run() {
            String data=taskSearch.getText().toString().trim();
            ArrayList<Schedule> searchList = new ArrayList<>();
            //防止请求出错闪退
            if (dataList!=null){
                for (int i=0;i<dataList.size();i++){
                    try {
                        Shop shop=db.selector(Shop.class).where("ID","=",dataList.get(i).getShopID()).findFirst();
                        String time=dataList.get(i).getSchStartTime().replaceAll("-","").replace("T"," ");
                        if (shop!=null){
                            if (shop.getShopName().contains(data)||time.contains(data)){
                                searchList.add(dataList.get(i));
                            }
                        }
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                }
                if (searchList.size()<=0){
                    BaseActivity.showAnimaDialog(EvaluationMianActivity.this,"未查询到数据");
                }

                setmyAdapter(searchList);
                myRecycle.setAdapter(adapter);
            }
            else{
                BaseActivity.showAnimaDialog(EvaluationMianActivity.this,"当前无数据查询");
                return;
            }
        }
    };

    /*根据不同的标识查询不通的数据*/
    public void LoadDate(String time){

        dataList=new ArrayList<>();
        pdialog=new ProgressDialog(this);
        pdialog.setMessage("加载中.....");
        pdialog.setCanceledOnTouchOutside(false);
        pdialog.show();
        try {
            if (LOADWHAT==1){

                dataList=db.selector(Schedule.class).where("schStartTime","like",time+"%")
                        .and(WhereBuilder.b("toUserId","=",MainActivity.id).or("shopmanId","=",MainActivity.id))
                        .and("states","in",new int[]{2,3,4})
                        .and("title","!=","休息")
                        .and("title","!=","年假")
                        .and("title","!=","其他假")
                        .orderBy("states")
                        .orderBy("schStartTime")
                        .findAll();
//                List<Schedule> schedules = db.selector(Schedule.class).where("shopmanId","=", MainActivity.id)
//                        .and("states","in",new int[]{2,3,4})
//                        .and("schStartTime","like",time+"%")
//                        .and("title","!=","休息")
//                        .and("title","!=","年假")
//                        .and("title","!=","其他假")
//                        .orderBy("states")
//                        .orderBy("schStartTime")
//                        .findAll();
//             if (dataList.size()>0){
//                 for (int k=0;k<dataList.size();k++){
//                     if (schedules.size()>0){
//                         for (int j=0;j<schedules.size();j++){
//                             if (dataList.get(k).)
//                         }
//                     }
//                 }
//             }


            }else{//查询门店
                if(shopid==0) {
                    dataList=db.selector(Schedule.class).where("schStartTime","like",time+"%")
                            .and(WhereBuilder.b("toUserId","=",MainActivity.id).or("shopmanId","=",MainActivity.id))
                            .and("states","in",new int[]{2,3,4})
                            .and("title","!=","休息")
                            .and("title","!=","年假")
                            .and("title","!=","其他假")
                            .orderBy("states")
                            .orderBy("schStartTime")
                            .findAll();
                }
                else{
                    dataList = db.selector(Schedule.class).where("toUserId", "=", MainActivity.id)
                            .and("shopID","=",shopid)
                            .and("states", "in", new int[]{1, 2, 3, 4})
                            .and("schStartTime", "like", time + "%")
                            .and("title", "!=", "休息")
                            .and("title", "!=", "年假")
                            .and("title", "!=", "其他假")
                            .orderBy("states")
                            .orderBy("schStartTime")
                            .findAll();
                }
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        pdialog.dismiss();
        //判断是否有数据显示
        if (dataList!=null && dataList.size()!=0){
            myRecycle.setVisibility(View.VISIBLE);
            setmyAdapter(dataList);
            myRecycle.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            erroLinear.setVisibility(View.GONE);
            try {
                loadSchScore();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            erroLinear.setVisibility(View.VISIBLE);
            erroText.setText("该月没有任务信息");
            myRecycle.setVisibility(View.GONE);
        }

    }

    public void setmyAdapter(List<Schedule> list){
        adapter=new ScheduleRecycleAdapter(list, EvaluationMianActivity.this, new ScheduleRecycleAdapter.MyCallBackClickListener() {
            @Override
            public void onEditorClick(Schedule schedule, int position) {

                schid = schedule.getID();
                        /*跳转展示页面，传递的schid进行查询数据库*/
                Intent in=new Intent(EvaluationMianActivity.this,WrittingEvaluationListActivity.class);
                in.putExtra("rrschid",schid);
                startActivityForResult(in,201);
            }
            @Override
            public void onLookClick(Schedule schedule, int position) {
                Intent in=new Intent(EvaluationMianActivity.this,LookEvaDetialActivity.class)
                        .putExtra("schid",schedule.getID());
                startActivity(in);
            }

            @Override
            public void onSignClick(Schedule schedule, int position) {
                Intent in=new Intent(EvaluationMianActivity.this,signuppanel.class);
                in.putExtra("rrschid",schid);
                startActivityForResult(in,100);
            }

            @Override
            public void onSubmitClick(Schedule schedule, int position) {
                schid=schedule.getID();
                try{
                    List<tempLostRR> rr;
                    rr=db.selector(tempLostRR.class).where("schId","=",schid).findAll();
                    Schedule thisSch=db.selector(Schedule.class).where("ID","=",schid+"").findFirst();
                    if(thisSch.getStates()>1) {
                        if(thisSch.getStates()>2)
                        {
                            Intent in = new Intent(EvaluationMianActivity.this, SendMailActivity.class).putExtra("schId", schedule.getID());
                            startActivityForResult(in, 101);
                        }
                        else if (rr == null || rr.size() == 0) {
                            showMessageOKCancel("该评估表尚未填写任何失分项,是否提交？", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent in = new Intent(EvaluationMianActivity.this, SendMailActivity.class).putExtra("schId", schid);
                                    startActivityForResult(in, 101);
                                }
                            });
                            //showToast("");
                        } else {
                            Intent in = new Intent(EvaluationMianActivity.this, SendMailActivity.class).putExtra("schId", schedule.getID());
                            startActivityForResult(in, 101);
                        }
                    }
                    else
                    {
                        BaseActivity.showAnimaDialog(EvaluationMianActivity.this,"任务尚未开始请先开始任务！");
                    }
                }catch (DbException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode==100){
            if(data!=null){
                String returl=data.getStringExtra("returl");
                if(returl!=null)
                {
                    CommonMapBean cmb=new CommonMapBean();
                    cmb.setCmValue(returl);
                    cmb.setCmType("门店签名");
                    cmb.setIndexNum(schid+"");
                    try {
                        db.saveOrUpdate(cmb);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        switch (requestCode){
            case 101:
            case 201:
                String  lmonth;
                if (month<10){
                    lmonth="0"+month;
                }else{
                    lmonth=month+"";
                }
                String time = year+"-"+lmonth;
                LoadDate(time);
                adapter.notifyDataSetChanged();
                myCollap.setTitle(shopName+"评估 "+"("+month+"月"+")");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.closeDialog:
                if(dialog!=null)
                    dialog.dismiss();
                break;
            case R.id.MoreBtn:
                dialog = new Dialog(this);
                View view = LayoutInflater.from(this).inflate(R.layout.efficdialog, (ViewGroup) getWindow().getDecorView(),false);
                TopDialogUtils.showTopDialog(this,dialog,view,5);
                Button closedialog = (Button) view.findViewById(R.id.closeDialog);
                closedialog.setOnClickListener(this);
                TextView lastMonth = (TextView) view.findViewById(R.id.lastMonth);
                lastMonth.setOnClickListener(this);
                TextView nowMonth = (TextView) view.findViewById(R.id.nowMonth);
                nowMonth.setOnClickListener(this);
                TextView nextMonth = (TextView) view.findViewById(R.id.nextMonth);
                nextMonth.setOnClickListener(this);
               TextView ManagerTask= (TextView) view.findViewById(R.id.ManagerTask);
                ManagerTask.setOnClickListener(this);
                if (chechLodaId==1) ManagerTask.setText("我的评估");
                else ManagerTask.setText("职能评估");
                dialog.show();
                break;
            //上月
            case R.id.lastMonth:
                dialog.dismiss();
                if (month==1){
                    month=12;
                    year=year-1;
                    if (thisyear==year)
                        myCollap.setTitle(shopName+"评估 "+"("+(month)+"月"+")");
                    else
                        myCollap.setTitle(shopName+"评估 "+"("+(year)+"年"+month+"月"+")");
                    String lastmth = new StringBuffer().append((year)).append("-").append(month).toString();
                    if (chechLodaId==0)
                        LoadDate(lastmth);
                    else
                        upManagerInfo();
                }else{
                    month=month-1;
                    if (thisyear==year)
                        myCollap.setTitle(shopName+"评估 "+"("+(month)+"月"+")");
                    else
                        myCollap.setTitle(shopName+"评估 "+"("+(year)+"年"+month+"月"+")");
                    String  lmonth;
                    if (chechLodaId==0)
                        LoadDate(searchData(month));
                    else
                        upManagerInfo();
                }
                break;
            //下月
            case R.id.nextMonth:
                dialog.dismiss();
              if (month==12){
                  month=1;
                  year=year+1;
                  if (thisyear==year)
                      myCollap.setTitle(shopName+"评估 "+"("+(month)+"月"+")");
                  else
                      myCollap.setTitle(shopName+"评估 "+"("+(year)+"年"+month+"月"+")");
                  String nextmth = new StringBuffer().append(year).append("-").append("0"+month).toString();
                  if (chechLodaId==0)
                      LoadDate(nextmth);
                  else
                      upManagerInfo();

              }else{
                  month=month+1;
                  if (thisyear==year)
                      myCollap.setTitle(shopName+"评估 "+"("+(month)+"月"+")");
                  else
                      myCollap.setTitle(shopName+"评估 "+"("+(year)+"年"+month+"月"+")");
                  String lmonth;
                  if (chechLodaId==0)
                      LoadDate(searchData(month));
                  else
                      upManagerInfo();
              }
                break;
            case R.id.nowMonth:
                dialog.dismiss();
                year=thisyear;
                month=thismonth;
                myCollap.setTitle(shopName+"评估 "+"("+month+"月"+")");
                if (chechLodaId==0)
                    LoadDate(currentDate);
                else
                    upManagerInfo();
                break;
            case R.id.ManagerTask:
                dialog.dismiss();
                //得到新的网络数据
                if (chechLodaId == 0) {
                    chechLodaId=1;
                    upManagerInfo();
                }else{
                    chechLodaId=0;
                    LoadDate(searchData(month));
                }
                break;
        }
    }

    public String searchData(int month){
        String lmonth;
        if (month<10){
            lmonth="0"+month;
        }else{
            lmonth=month+"";
        }
        return  new StringBuffer().append(year).append("-").append(lmonth).toString();

    }

    /**
     * 加载职能数据
     */
    public void upManagerInfo(){
        pdialog=new ProgressDialog(this);
        pdialog.setCanceledOnTouchOutside(false);
        pdialog.setMessage("加载中.....");
        pdialog.show();
        Map<String,String> map=new HashMap<>();
        map.put("task","loadOtherOESchedule");
        map.put("empid",MainActivity.id+"");
        map.put("month",month+"");
        map.put("year",year+"");
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    String[] res = result.split("\\|");
                    if (res[0].equals("200")) {
                        Gson gson = new Gson();
                        Type typeList = new TypeToken<ArrayList<Schedule>>() {
                        }.getType();
                       dataList = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                        if (dataList.size() == 0) {
                            erroLinear.setVisibility(View.VISIBLE);
                            erroText.setText("还有任何数据");
                            myRecycle.setVisibility(View.GONE);
                        } else {
                            erroLinear.setVisibility(View.GONE);
                            myRecycle.setVisibility(View.VISIBLE);
                            setmyAdapter(dataList);
                            myRecycle.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
                        }
                    }else{
                        myRecycle.setVisibility(View.GONE);
                        erroLinear.setVisibility(View.VISIBLE);
                        erroText.setText("数据请求错误");
                    }
                    pdialog.dismiss();
                }
                @Override
                public void onFailture() {
                    pdialog.dismiss();
                    myRecycle.setVisibility(View.GONE);
                    erroLinear.setVisibility(View.VISIBLE);
                    erroText.setText("网络失去连接");
                    chechLodaId=0;
                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
            pdialog.dismiss();
            myRecycle.setVisibility(View.GONE);
            erroLinear.setVisibility(View.VISIBLE);
            erroText.setText("网络失去连接");
        }

    }
    //查询不含score的sch
    private String getNotScore(){
        StringBuilder str = new StringBuilder();
        noScoreList = new ArrayList<>();
        if (dataList!=null&&dataList.size()>0){
            for (int i = 0;i<dataList.size();i++){
                Schedule sch = dataList.get(i);
                if(sch.getSubtitle()!=null&&sch.getSubtitle().contains(",")){
                    continue;
                }else{
                    noScoreList.add(sch);
                    str.append(sch.getID()).append(",");
                }
            }
        }
        if (str.length()>0){
           return str.toString().substring(0,str.length()-1);
        }else{
            return "null";
        }
    }

    private void loadSchScore() throws IOException {
        mainList = new ArrayList<>();
        Map<String,String> map = new HashMap<>();
        map.put("task","getSchScoreById");
        String schStr = getNotScore();
        if (schStr.equals("null")){
            return;
        }else{
            map.put("schid",schStr);
        }
        OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
            @Override
            public void onSuccess(String result) {
                String[] array = result.split("\\|");
                if (array[0].equals("200")){
                    Log.e("result",array[3]);
                    Gson gson = new Gson();
                    Type typeList = new TypeToken<ArrayList<tReportMain>>() {
                    }.getType();
                    mainList =gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                    updateScor();
                }
            }

            @Override
            public void onFailture() {

            }
        },map);

    }

    public void updateScor(){
        if (mainList!=null&& mainList.size()>0){
           for (int k = 0;k<mainList.size();k++){
               tReportMain main = mainList.get(k);
               if (dataList!=null&&dataList.size()>0){
                   for (int i = 0;i<dataList.size();i++){
                       Schedule sch = dataList.get(i);
                       if(sch.getSubtitle()!=null&&sch.getSubtitle().contains(",")){
                           continue;
                       }else{
                           if (mainList.get(k).getSchId() == sch.getID()){
                               sch.setSubtitle(mainList.get(k).getScore()+","+mainList.get(k).getLevel());
                               if (chechLodaId==0){
                                   try {
                                       db.saveOrUpdate(sch);
                                   } catch (DbException e) {
                                       e.printStackTrace();
                                   }
                               }
                           }
                       }
                   }
               }
           }
        }
        if (adapter!=null){
            adapter.notifyDataSetChanged();
        }
    }


    //限制回车键
    public static void LimitsEditEnter(EditText et) {
        et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });
    }

    @SuppressLint("PrivateApi")
    @Override
    protected void onDestroy() {
        super.onDestroy();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        try {
            InputMethodManager.class.getDeclaredMethod("windowDismissed", IBinder.class).invoke(imm,
                    getWindow().getDecorView().getWindowToken());
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
                finish();
            }
        return super.onKeyDown(keyCode, event);
    }
}
